﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Data.Common;

using TSV.Library.Common;
using TSV.Models;

namespace TSV.Areas.Administration.Models
{
    public class UserAdminDao : BaseDao
    {
        #region Private Fields

        private AuthenticateDao auDao = new AuthenticateDao();
        #endregion

        #region Public methods

        /// <summary>
        /// Get By Id
        /// </summary>
        /// <param name="userAdminId"></param>
        /// <returns></returns>
        public UserAdmin GetById(int userAdminId)
        {
            return dbContext.UserAdmins.Where(p => (
                (p.UserAdminId == userAdminId) &&
                (p.DeleteFlag == false))).FirstOrDefault<UserAdmin>();
        }

        /// <summary>
        /// Get user_group by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public User_Group GetUser_Group(int id)
        {
            return dbContext.User_Groups.Where(p => p.ID == id).FirstOrDefault<User_Group>();
        }

        /// <summary>
        /// Get By Id
        /// </summary>
        /// <param name="userAdminId"></param>
        /// <returns></returns>
        public UserAdmin GetByUserName(string userName)
        {
            return dbContext.UserAdmins.Where(p => (
                (p.UserName == userName) &&
                (p.DeleteFlag == false))).FirstOrDefault<UserAdmin>();
        }


        /// <summary>
        /// Get user_group by user name and group Id
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public User_Group GetUser_Group(int userId, int groupId)
        {
            return dbContext.User_Groups.Where(u => u.UserAdminId == userId && u.GroupId == groupId).SingleOrDefault<User_Group>();
        }

        /// <summary>
        /// Get List
        /// </summary>
        /// <param name="userAdminId"></param>
        /// <returns></returns>
        public List<UserAdmin> GetList(string userName)
        {
            return dbContext.UserAdmins.Where(p => (
                (p.UserName.Contains(userName)) &&
                (p.DeleteFlag == false))).Take(Constants.AUTO_COMPLETE_ITEMS).ToList<UserAdmin>();
        }

        /// <summary>
        /// Get User Admin List
        /// </summary>
        /// <returns></returns>
        public List<UserAdmin> GetList()
        {
            return dbContext.UserAdmins.Where(p => p.DeleteFlag == false)
                .OrderByDescending(p => p.UserName).ToList<UserAdmin>();
        }

        public List<User_Group> GetListUser_Group()
        {
            return dbContext.User_Groups.ToList<User_Group>();
        }

        public List<User_Group> Sort(List<User_Group> list, string sortColumn, string sortOrder)
        {
            int order;

            if (sortOrder == "desc")
            {
                order = -1;
            }
            else
            {
                order = 1;
            }
            switch (sortColumn)
            {
                case "UserName":
                    list.Sort(
                         delegate(User_Group m1, User_Group m2)
                         { return m1.UserAdmin.UserName.CompareTo(m2.UserAdmin.UserName) * order; });
                    break;
                case "GroupName":
                    list.Sort(
                         delegate(User_Group m1, User_Group m2)
                         { return m1.Group.GroupName.CompareTo(m2.Group.GroupName) * order; });
                    break;
                case "Active":
                    list.Sort(
                         delegate(User_Group m1, User_Group m2)
                         { return m1.IsActive.CompareTo(m2.IsActive) * order; });
                    break;
                case "CreatedBy":
                    list.Sort(
                         delegate(User_Group m1, User_Group m2)
                         { return m1.CreatedBy.CompareTo(m2.CreatedBy) * order; });
                    break;
                case "UpdatedBy":
                    list.Sort(
                         delegate(User_Group m1, User_Group m2)
                         { return m1.UpdatedBy.CompareTo(m2.UpdatedBy) * order; });
                    break;
            }

            return list;
        }

        /// <summary>
        /// Insert user admin and user group
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="groupId"></param>
        /// <param name="isActive"></param>
        /// <param name="principal"></param>
        /// <returns></returns>
        public Message Insert(string userName, string password, string groupId, bool isActive, AuthenticationProjectPrincipal principal)
        {
            Message msg = null;
            try
            {
                UserAdmin user = GetByUserName(userName);
                if (user == null)
                {
                    user = new UserAdmin();
                    user.UserName = userName;
                    user.Password = password;
                    user.DeleteFlag = false;
                    user.CreateDate = DateTime.Now;
                    user.UpdateDate = DateTime.Now;
                    user.CreatedBy = principal.UserData.UserName;
                    user.UpdatedBy = principal.UserData.UserName;

                    dbContext.UserAdmins.InsertOnSubmit(user);
                    dbContext.SubmitChanges();
                }

                int _groupId = int.Parse(groupId);

                User_Group user_group = GetUser_Group(user.UserAdminId, _groupId);
                if (user_group == null)
                {
                    user_group = new User_Group();
                    user_group.UserAdminId = user.UserAdminId;
                    user_group.GroupId = int.Parse(groupId);
                    user_group.IsActive = isActive;
                    user_group.CreateDate = DateTime.Now;
                    user_group.UpdateDate = DateTime.Now;
                    user_group.CreatedBy = principal.UserData.UserName;
                    user_group.UpdatedBy = principal.UserData.UserName;

                    dbContext.User_Groups.InsertOnSubmit(user_group);
                    dbContext.SubmitChanges();

                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Người dùng " + userName + " thuộc nhóm " + user_group.Group.GroupName, "thêm");
                }
                else
                {
                    msg = new Message(MessageConstants.E0020, MessageType.Error, "Người dùng " + userName + " thuộc nhóm " + user_group.Group.GroupName, "CSDL");
                }

            }
            catch (Exception)
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        /// <summary>
        /// Update user group
        /// </summary>
        /// <param name="objUI"></param>
        /// <returns></returns>
        public Message Update(string id, string userName, string groupId, bool isActive, AuthenticationProjectPrincipal principal)
        {
            Message msg = null;
            try
            {
                UserAdmin user = GetByUserName(userName);
                if (user == null)
                {
                    user = new UserAdmin();
                    user.UserName = userName;
                    user.DeleteFlag = false;
                    user.CreateDate = DateTime.Now;
                    user.UpdateDate = DateTime.Now;
                    user.CreatedBy = principal.UserData.UserName;
                    user.UpdatedBy = principal.UserData.UserName;

                    dbContext.UserAdmins.InsertOnSubmit(user);
                    dbContext.SubmitChanges();
                }

                int _groupId = int.Parse(groupId);

                User_Group user_group = GetUser_Group(user.UserAdminId, _groupId);

                if (user_group == null)
                {
                    user_group = GetUser_Group(int.Parse(id));
                }
                else if (user_group.ID.ToString() != id)
                {
                    msg = new Message(MessageConstants.E0020, MessageType.Error, "Người dùng " + userName + " thuộc nhóm " + user_group.Group.GroupName, "CSDL");
                }

                if (msg == null)
                {
                    if (user_group != null)
                    {
                        user_group.UserAdminId = user.UserAdminId;
                        user_group.GroupId = int.Parse(groupId);
                        user_group.IsActive = isActive;

                        user_group.UpdateDate = DateTime.Now;
                        user_group.UpdatedBy = principal.UserData.UserName;

                        dbContext.SubmitChanges();
                        msg = new Message(MessageConstants.I0001, MessageType.Info, "Người dùng " + userName + " thuộc nhóm " + user_group.Group.GroupName, "thêm");
                    }
                    else
                    {
                        msg = new Message(MessageConstants.E0020, MessageType.Error, "Người dùng " + userName + " thuộc nhóm " + user_group.Group.GroupName + " không", "CSDL");
                    }
                }

            }
            catch (Exception)
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }


        // <summary>
        /// Update user group
        /// </summary>
        /// <param name="objUI"></param>
        /// <returns></returns>
        public Message ChangePassword(UserAdmin user)
        {
            Message msg = null;
            try
            {                
                UserAdmin userAdmin = GetById(user.UserAdminId);
                if (userAdmin != null)
                {
                    userAdmin.Password = user.Password;
                    dbContext.SubmitChanges();
                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Người dùng '" + userAdmin.UserName + "'", "đổi mật khẩu");
                }
                else
                {
                    msg = new Message(MessageConstants.E0007, MessageType.Error);
                }
            }
            catch (Exception)
            {
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        public Message DeleteList(string ids)
        {
            Message msg = null;
            DbTransaction trans = null;
            try
            {
                dbContext.Connection.Open();
                trans = dbContext.Connection.BeginTransaction();
                dbContext.Transaction = trans;

                if (!string.IsNullOrEmpty(ids))
                {
                    DeleteList(ids, ref msg);
                }
                trans.Commit();
            }
            catch
            {
                if (trans != null) trans.Rollback();

                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }

        private void DeleteList(string ids, ref Message msg)
        {
            ids = ids.TrimEnd(',');
            string[] idArr = ids.Split(',');
            int total = idArr.Count();
            foreach (string id in idArr)
            {
                int intID = int.Parse(id);
                User_Group user_group = GetUser_Group(intID);
                if (user_group != null)
                {
                    UserAdmin user = user_group.UserAdmin;
                    dbContext.User_Groups.DeleteOnSubmit(user_group);

                    dbContext.SubmitChanges();
                    if (user.User_Groups.Count == 0)
                    {
                        dbContext.UserAdmins.DeleteOnSubmit(user);
                        dbContext.SubmitChanges();
                    }
                }
                else
                {
                    total--;
                }
            }
            msg = new Message(MessageConstants.I0001, MessageType.Info, total.ToString() + " tài khoản", "xóa");
        }

        /// <summary>
        /// Get Active By Id
        /// </summary>
        /// <param name="userAdminId"></param>
        /// <returns></returns>
        public UserAdmin GetActiveUserById(int userAdminId)
        {
            return dbContext.UserAdmins.Where(p => (
                (p.UserAdminId == userAdminId) &&
                (p.DeleteFlag == false))).FirstOrDefault<UserAdmin>();
        }

        /// <summary>
        /// Check Login
        /// </summary>
        /// <param name="objUI"></param>
        /// <returns></returns>
        public UserAdmin CheckLogin(UserAdmin objUI)
        {
            UserAdmin objRes = null;
            objRes = dbContext.UserAdmins.Where(p => (
                (p.UserName == objUI.UserName) &&
                (p.DeleteFlag == false))).FirstOrDefault<UserAdmin>();

            return objRes;
        }

        #endregion
    }
}